import React, {useState, useEffect, useRef,
    useMemo, useImperativeHandle, forwardRef } from "react";
import { Modal } from "antd";
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor'
import { MouseEvent } from "react";
import './my-editor.css'
// import '@wangeditor/editor/dist/css/style.css'
import {skip, Subject} from "rxjs";

interface PropsType {
   style?: React.CSSProperties;
   placeholder?: string;
   onContentChange?: (html: string) => void;
   defaultHtml?: string;
}

export const MyEditor = forwardRef<any, PropsType>(({
    style= {},
    placeholder = '请输入',
    onContentChange = () => {},
    defaultHtml= '',
}, ref) => {
    // editor 实例
    const [editor, setEditor] = useState<IDomEditor | null>(null)
    // 编辑器内容
    const [html, setHtml] = useState(defaultHtml)
    // toolbar 配置
    const toolbarConfig: Partial<IToolbarConfig> = {
        excludeKeys: [
            'group-image', "insertVideo", "insertTable",
            "codeBlock", "fullScreen", "insertLink"
        ]
    }

    // 父组件可以拿到值
    useImperativeHandle(ref, () => ({editor}))

    const eventEmit = useMemo(() => new Subject<string>(), [])


    useEffect(() => {
        const subscription = eventEmit.pipe(
            skip(1)
        ).subscribe(v => {
            onContentChange(v);
        })
        return () => {
            subscription.unsubscribe();
        }
    }, [])
    // 编辑器配置
    const editorConfig: Partial<IEditorConfig> = {
        placeholder, autoFocus: true,
    }
    // 及时销毁
    useEffect(() => {
        return () => {
            if (editor === null) return;
            editor.destroy();
            setEditor(null)
        }
    }, [editor])

    const [pos, setPos]  = useState<Partial<{
        left: number;
        top: number;
        width: number;
        height: number
    }>>({})


    function clickEditorText(e: MouseEvent<HTMLDivElement>) {
        const el = editorTextEl.current as any as HTMLDivElement;
        const { top, left, width, height } = el.getBoundingClientRect()
        setPos(pos => ({...pos, width: width > 900 ? width : 900, left, top, height}))
        setIsModalOpen(true)
    }
    function saveText(e: MouseEvent<HTMLButtonElement>) {
        if (editor) {
            if (editor.isEmpty()) {
                setHtml('')
            } else {
                setHtml(editor.getHtml())
            }
        }
        setIsModalOpen(false)
    }
    const [isModalOpen, setIsModalOpen] = useState(false)
    const editorTextEl = useRef(null)

    useEffect(() => {
        if (!isModalOpen) {
            eventEmit.next(html)
        } else {
            if (editor) {
                editor.setHtml(defaultHtml)
            }
        }
    }, [isModalOpen])

    return <>
        <Modal
            width={pos.width}
            style={{top: pos.top}}
            open={isModalOpen}
            closable={false}
            maskClosable={false}
            okText={'保存'}
            cancelText={'取消'}
            // getContainer={false}
            onCancel={() => {
             setIsModalOpen(false)
            }}
            onOk={saveText}
        >
            <div style={{margin: 10, border: '1px solid #ccc'}}>
                <Toolbar
                    editor={editor}
                    defaultConfig={toolbarConfig}
                    mode="simple"
                    style={{ borderBottom: '1px solid #ccc' }}
                />
                <Editor
                    defaultConfig={editorConfig}
                    value={html}
                    onCreated={setEditor}
                    // onChange={editor => setHtml(editor.getHtml())}
                    mode="simple"
                    style={{ minHeight: '200px', overflowY: 'hidden' }}
                />
            </div>
        </Modal>
        <div
            ref={editorTextEl}
            // style={{ display: html ? "block" : 'none' }}
            className='wang-edit-container'
            onClick={clickEditorText}
            dangerouslySetInnerHTML={{__html: html}}>
        </div>
    </>
});
